package com.yehebl.orm.util;

import com.yehebl.orm.config.IConfig;
import com.yehebl.orm.enums.SqlLogMode;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 根据模式打印sql
 */
public class SqlLogUtil {
    private static void showSql(IConfig config, String sql) {
        config.printSql(sql);
    }

    private static String getFormatSql(IConfig config, String sql) {
        String returnStr;
        if (SqlLogMode.ALL_FORMAT.equals(config.getSqlLogModeByRunMode())
                || SqlLogMode.SQL_FORMAT.equals(config.getSqlLogModeByRunMode())) {
            returnStr = "\n" + FormatSqlUtil.getFormatSqlUtil().format(sql);
        } else {
            returnStr = sql;
        }
        return returnStr;
    }

    private static void getParameterSqlLog(IConfig config, String sql, Object... objs) {
        if (SqlLogMode.NONE.equals(config.getSqlLogModeByRunMode())) {
            return;
        }
        String returnSql = getFormatSql(config, sql);
        if (SqlLogMode.ALL.equals(config.getSqlLogModeByRunMode())
                || SqlLogMode.ALL_FORMAT.equals(config.getSqlLogModeByRunMode())) {
            StringBuilder newSqlStr = new StringBuilder(returnSql);
            if (objs == null) {
                showSql(config, returnSql);
                return;
            }
            int maxIndex = 0;
            for (Object obj : objs) {
                int index = newSqlStr.indexOf("?", maxIndex);
                if (index == -1) {
                    break;
                }
                if (obj == null) {
                    newSqlStr.replace(index, index + 1, "null");
                    maxIndex = index + 1 + "null".length();
                    continue;
                }
                if (obj instanceof Date) {
                    SimpleDateFormat sdf = DateUtil.getSimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
                    String dateStr = sdf.format(obj);
                    newSqlStr.replace(index, index + 1, "'" + dateStr + "'");
                    maxIndex = index + 1 + dateStr.length();
                    continue;
                }
                int maxIndex1 = index + 1 + obj.toString().length();
                if (obj instanceof Integer || obj instanceof Long || obj instanceof Float || obj instanceof Double || obj instanceof Short) {
                    newSqlStr.replace(index, index + 1, "" + obj + "");
                    maxIndex = maxIndex1;
                    continue;
                }
                newSqlStr.replace(index, index + 1, "'" + obj + "'");
                maxIndex = maxIndex1;
            }
            showSql(config, newSqlStr.toString());

        }
    }

    public static void print(IConfig config, String sql, Object... obj) {
        getParameterSqlLog(config, sql, obj);
    }

}
